package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.OrderReceiveInfo;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.fragment.OrderReceiveInfoSelector;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.OrderService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.utils.DateUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderDetailActivity extends BaseActivity implements OrderReceiveInfoSelector.InteractionListener {
    private static final String TAG = "OrderDetailActivity";
    private static final int REQUEST_CODE_REFUND = 0;
    private static final int REQUEST_CODE_ORDER_SEND = 1;

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_order_id)
    TextView tv_orderId;
    @BindView(R.id.et_phone)
    TextView et_phone;
    @BindView(R.id.et_contact)
    EditText et_contact;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.btn_select_address)
    Button btn_selectAddress;
    @BindView(R.id.btn_pay_order)
    Button btn_commit;
    @BindView(R.id.btn_cancel_order)
    Button btn_cancelOrder;
    @BindView(R.id.tv_order_status)
    TextView tv_orderStatus;
    @BindView(R.id.rl_expiry_time)
    RelativeLayout rl_expiryTime;
    @BindView(R.id.tv_expiry_time)
    TextView tv_expiryTime;
    @BindView(R.id.ll_order_receive_info)
    LinearLayout ll_orderReceiveInfo;
    @BindView(R.id.rl_send_status)
    RelativeLayout rl_sendStatus;

    @BindView(R.id.tv_send_status)
    TextView tv_sendStatus;
    @BindView(R.id.tv_order_type)
    TextView tv_orderType;
    @BindView(R.id.ll_deposit)
    LinearLayout ll_deposit;
    @BindView(R.id.tv_deposit)
    TextView tv_deposit;
    @BindView(R.id.btn_order_send)
    Button btn_orderSend;

    private Orders order;
    private String contact;
    private String phone;
    private String address;
    private Topic topic;
    private boolean isSeller;
    private User loginUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(v -> finish());
        order = getIntent().getParcelableExtra(Constant.EXTRA_INFO_ORDER);
        loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        isSeller = loginUserInfo.getuId().equals(order.getSellerId());
        topic = order.getTopic();
        if (order == null) {
            throw new RuntimeException("order can't empty");
        }
        boolean syncOrderData = getIntent().getBooleanExtra("syncOrderData", false);
        setViewAndEvent();
        //判断是否需要同步服务端的数据
        if (syncOrderData) {
            syncOrderData(order.getId());
        }
    }

    private void setViewAndEvent() {

        tv_topicTitle.setText(order.getTitle());
        tv_topicTitle.setOnClickListener(v -> toTopicDetail());
        tv_amount.setText(Utils.moneyFormat(order.getAmount()));
        tv_orderId.setText(order.getId());
        hideSomeView();
        boolean isAuctionOrder = order.getType() == Constant.ORDER_TYPE_TO_AUCTION_TOPIC;
        if (isAuctionOrder) {
            tv_orderType.setText("拍卖订单");
            ll_deposit.setVisibility(View.VISIBLE);
            tv_deposit.setText(Utils.moneyFormat(order.getDeposit()));
        } else {
            tv_orderType.setText("普通订单");

        }

        switch (order.getStatus()) {

            case Constant.ORDER_STATUS_CONFLICT:
                setEditViewLoseFocus();
                tv_orderStatus.setText("问题处理中...");
                showCheckRefund();
                break;
            case Constant.ORDER_STATUS_INIT://对于普通订单，初始化
                tv_orderStatus.setText("等待支付");
                if (isSeller) {
                    showCancelOrder();
                } else {
                    showCancelOrder();
                    showPayOrder();
                    showSelectAddress();
                    showOrderReceiveInfo();
                }
                break;
            case Constant.ORDER_STATUS_OFFER_SUCCESS://对于拍卖订单，出价成功
                tv_orderStatus.setText("等待支付");
                //拍卖的订单需要显示支付截止日期
                showPayExpiryLayout();
                if (isSeller) {
                    showCancelOrder();
                } else {
                    showCancelOrder();
                    showPayOrder();
                    showSelectAddress();
                    showOrderReceiveInfo();
                }
                break;
            case Constant.ORDER_STATUS_PAID:
                tv_orderStatus.setText("待发货");
                if (isSeller) {
                    //当一个订单已经支付，对于卖方来说，可以取消，也可以选择发货
                    showCancelOrder();
                    showOrderSend();
                } else {
                    showOrderReceiveInfo();
                    setEditViewLoseFocus();
                    showRefund();
                }
                break;
            case Constant.ORDER_STATUS_SENT:
                tv_orderStatus.setText("已发货");
                //已经发货，显示查看发货详情
                if (!isSeller) {
                    showRefund();
                }
                showOrderExpressDetail();

                break;
            case Constant.ORDER_STATUS_EXPIRED:
                tv_orderStatus.setText("已过期");
                break;
            case Constant.ORDER_STATUS_BUYER_CANCELLED:
                if (isAuctionOrder) {
                    tv_orderStatus.setText("买方取消订单，已扣除订单保证金予卖方，交易终止");
                } else {
                    tv_orderStatus.setText("买方取消订单，交易终止");
                }

                break;
            case Constant.ORDER_STATUS_SELLER_CANCELLED:
                tv_orderStatus.setText("卖方已取消订单，交易终止");
//                if (!isSeller) {
//                    showOrderReceiveInfo();
//                    setEditViewLoseFocus();
//                }
                break;
            case Constant.ORDER_STATUS_SELLER_CANCEL_ON_PAID:
                tv_orderStatus.setText("卖方取消订单，交易结束，订单金额已返还至买方账户余额");
                break;

            case Constant.ORDER_STATUS_TRADE_SUCCESS:
//                showOrderReceiveInfo();
//                setEditViewLoseFocus();
                tv_orderStatus.setText("交易成功");
                break;
            case Constant.ORDER_STATUS_REFUNDING:
                tv_orderStatus.setText("退款中...");
//                showOrderReceiveInfo();
//                setEditViewLoseFocus();
                if (isSeller) {
                    showCheckRefund();
                    showAgreeRefund();

                } else {
                    showCheckRefund();
                }

                //退款中，肯定已经支付了，这时候应该显示发货状态
                showSendStatus();


                break;

            case Constant.ORDER_STATUS_REFUND_COMPLETED:

                tv_orderStatus.setText("退款完成，交易结束");
                break;

            case Constant.ORDER_STATUS_REFUSE_REFUND:
                tv_orderStatus.setText("卖方拒绝退款");

                if (isSeller) {
                    showCheckRefund();
                    showAgreeRefund();
                } else {
                    showCheckRefund();
                }
                break;
        }

    }

    //显示物流详情
    private void showOrderExpressDetail() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("查看发货详情");
        btn_commit.setOnClickListener(v -> orderSend());
    }

    //退款状态中才显示发货状态
    private void showSendStatus() {
        if (order.getSendStatus() != null) {
            rl_sendStatus.setVisibility(View.VISIBLE);
            switch (order.getSendStatus()) {
                case Constant.ORDER_SEND_STATUS_WAIT_SEND:
                    tv_sendStatus.setText("未发货");
                    if (isSeller) {
                        showOrderSendSmallButton();
                    }
                    break;
                case Constant.ORDER_SEND_STATUS_SENT:
                    tv_sendStatus.setText("已发货");
                    showReceiveExpiryLayout();
                    if (!isSeller) {
                        showReceiveOrders();
                    }
                    break;
                case Constant.ORDER_SEND_STATUS_RECEIVED:
                    tv_sendStatus.setText("已收货");
                    break;
            }


        }
    }

    //退款状态中，显示小的 发货按键
    private void showOrderSendSmallButton() {
        btn_orderSend.setVisibility(View.VISIBLE);
        btn_orderSend.setOnClickListener(v -> orderSend());

    }


    private OrderReceiveInfo getOrderReceiveInfo() {
        //如果订单中有携带 联系人 联系电话 地址 等信息，就显示订单中携带的信息，
        if (order.getContact() != null) {
            return new OrderReceiveInfo(order.getContact(), order.getPhone(), order.getAddress());
        }
        // 用户是否有订单收货信息，如果有，就显示第一个，
        List<OrderReceiveInfo> orderReceiveInfoList = loginUserInfo.getOrderReceiveInfoList();
        if (orderReceiveInfoList != null && orderReceiveInfoList.size() != 0) {
            return orderReceiveInfoList.get(0);
        }
        // 以用户基本资料中的信息填充
        return new OrderReceiveInfo(loginUserInfo.getUsername(), loginUserInfo.getPhone(), loginUserInfo.getArea());

    }

    private void showOrderReceiveInfo() {
        OrderReceiveInfo orderReceiveInfo = getOrderReceiveInfo();
        ll_orderReceiveInfo.setVisibility(View.VISIBLE);
        et_contact.setText(orderReceiveInfo.getContact());
        et_phone.setText(orderReceiveInfo.getPhone());
        et_address.setText(orderReceiveInfo.getAddress());
    }

    //隐藏一些不确定是否会用到的View
    private void hideSomeView() {
        btn_orderSend.setVisibility(View.GONE);
        rl_sendStatus.setVisibility(View.GONE);
        ll_deposit.setVisibility(View.GONE);
        rl_expiryTime.setVisibility(View.GONE);
        btn_cancelOrder.setVisibility(View.GONE);
        btn_selectAddress.setVisibility(View.GONE);
        btn_commit.setVisibility(View.GONE);
        ll_orderReceiveInfo.setVisibility(View.GONE);
    }

    private void showPayOrder() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("支付订单");
        btn_commit.setOnClickListener(v -> preparePay());
    }

    private void showCancelOrder() {
        btn_cancelOrder.setVisibility(View.VISIBLE);
        btn_cancelOrder.setText("取消订单");
        if (isSeller) {
            if (order.getStatus() == Constant.ORDER_STATUS_PAID) {

                btn_cancelOrder.setOnClickListener(v -> cancelPaidOrder());
            } else {
                btn_cancelOrder.setOnClickListener(v -> cancelOrder());
            }

        } else {
            btn_cancelOrder.setOnClickListener(v -> prepareCancelOrder());
        }
    }


    //显示发起退款按键
    private void showRefund() {
        btn_cancelOrder.setVisibility(View.VISIBLE);
        btn_cancelOrder.setText("发起退款");
        btn_cancelOrder.setOnClickListener(v -> toRefundDetail());
    }

    //显示查看退款按键
    private void showCheckRefund() {
        btn_cancelOrder.setVisibility(View.VISIBLE);
        btn_cancelOrder.setText("查看退款");
        btn_cancelOrder.setOnClickListener(v -> toRefundDetail());
    }

    //显示同意退款按键
    private void showAgreeRefund() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("同意退款");
        btn_commit.setOnClickListener(v -> agreeRefund());
    }

    //显示 确认收货按键
    private void showReceiveOrders() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("确认收货");
        btn_commit.setOnClickListener(v -> receiveOrder());
    }

    private void showSelectAddress() {
        btn_selectAddress.setVisibility(View.VISIBLE);
        btn_selectAddress.setText("选择地址");
        btn_selectAddress.setOnClickListener(v -> {
            OrderReceiveInfoSelector orderReceiveInfoSelector = OrderReceiveInfoSelector.newInstance();
            orderReceiveInfoSelector.show(getSupportFragmentManager(), "");
            orderReceiveInfoSelector.setListener(OrderDetailActivity.this);
        });
    }

    private void showOrderSend() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("发货");
        btn_commit.setOnClickListener(v -> orderSend());
    }

    private void onOderRefund() {


    }

    private void toTopicDetail() {
        if (topic != null) {
            startActivity(new Intent(this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
        } else {
            getFullTopic(order.gettId());
        }
    }

    private void setEditViewLoseFocus() {
        et_contact.setFocusable(false);
        et_phone.setFocusable(false);
        et_address.setFocusable(false);
    }

    /**
     * 显示过期时间
     */
    private void showPayExpiryLayout() {
        rl_expiryTime.setVisibility(View.VISIBLE);
        tv_expiryTime.setText(DateUtils.dateToString(order.getExpiryDate(), "yyyy-MM-dd HH:mm") + "，到期未支付将自动扣除保证金");
    }

    /**
     * 显示自动收货时间
     */
    private void showReceiveExpiryLayout() {
        rl_expiryTime.setVisibility(View.VISIBLE);
        tv_expiryTime.setText(DateUtils.dateToString(order.getExpiryDate(), "yyyy-MM-dd HH:mm") + "，到期将会自动收货");
    }


    private void syncOrderData(String orderId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .syncOrderData(orderId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 同步订单信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        order = body.toJavaObject(Orders.class);
                        order.setTopic(topic);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void preparePay() {

        if (et_contact.getText() == null) {
            showToast("联系人不能为空");
            return;
        }
        contact = et_contact.getText().toString();
        if (et_phone.getText() == null) {
            showToast("联系电话不能为空");
            return;
        }
        phone = et_phone.getText().toString();
        if (et_address.getText() == null) {
            showToast("收获地址不能为空");
            return;
        }
        address = et_address.getText().toString();
        //订单接收信息需要重新获取
        List<OrderReceiveInfo> orderReceiveInfoList = UserProfileManager.getInstance().getLoginUserInfo().getOrderReceiveInfoList();
        //判断订单接收信息是否是新增的信息
        boolean isNewOrderReceiveInfo = true;
        for (int i = orderReceiveInfoList.size() - 1; i >= 0; i--) {
            OrderReceiveInfo info = orderReceiveInfoList.get(i);
            // 联系人 地址 电话都相同，认定为旧的订单接收信息
            if (info.getContact().equals(contact) && info.getPhone().equals(phone) && info.getAddress().equals(address)) {
                isNewOrderReceiveInfo = false;
                break;
            }
        }
        if (isNewOrderReceiveInfo) {
            orderReceiveInfoList.add(new OrderReceiveInfo(order.getContact(), order.getPhone(), order.getAddress()));
            UserProfileManager.getInstance().setOrderReceiveInfoList(orderReceiveInfoList);
        }

        new PayUtils(order.getAmount(), this, payPassword -> payOrder(payPassword));
    }


    private void hideCommitButton() {
        btn_commit.setEnabled(false);
        btn_selectAddress.setVisibility(View.GONE);
        btn_cancelOrder.setVisibility(View.GONE);
    }

    /**
     * 取消订单
     */
    private void prepareCancelOrder() {

        if (!isSeller) {
            ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "买方主动取消订单会扣除订单保证金予卖方，确定取消订单吗", true);
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    cancelOrder();
                }
            });
            dialog.show();
        }

    }

    private void cancelOrder() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .cancelOrder(order.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.ORDER_STATUS_ERROR://这个情况应该不会出现
                                    showToast("当前订单状态已过时，正在同步最新订单状态");
                                    syncOrderData(order.getId());
                                    break;
                                case Constant.ORDER_INVALID:
                                    showToast("当前订单状态已过时，正在同步最新订单状态");
                                    syncOrderData(order.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        showToast(btn_cancelOrder, "取消订单完成");
                        if (isSeller) {
                            order.setStatus(Constant.ORDER_STATUS_SELLER_CANCELLED);
                        } else {
                            order.setStatus(Constant.ORDER_STATUS_BUYER_CANCELLED);
                        }
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }

    private void cancelPaidOrder() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .cancelPaidOrder(order.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.ORDER_STATUS_ERROR://这个情况应该不会出现
                                    showToast("当前订单状态已过时，正在同步最新订单状态");
                                    syncOrderData(order.getId());
                                    break;
                                case Constant.ORDER_INVALID:
                                    showToast("当前订单状态已过时，正在同步最新订单状态");
                                    syncOrderData(order.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        showToast(btn_cancelOrder, "取消订单完成");
                        order.setStatus(Constant.ORDER_STATUS_SELLER_CANCEL_ON_PAID);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 发起退款/修改退款
     */
    private void toRefundDetail() {
        startActivityForResult(new Intent(this, RefundActivity.class).putExtra(Constant.EXTRA_INFO_ORDER, order), REQUEST_CODE_REFUND);

    }


    private void payOrder(String payPassword) {
        progressBar.setVisibility(View.VISIBLE);
        Map<String, Object> body = new HashMap<>();
        order.setContact(contact);
        order.setPhone(phone);
        order.setAddress(address);
        Orders updateOrder = new Orders();
        updateOrder.setId(order.getId());
        updateOrder.setContact(contact);
        updateOrder.setPhone(phone);
        updateOrder.setAddress(address);
        body.put("order", updateOrder);
        body.put("payPassword", payPassword);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .payOrder(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(getString(R.string.balance_not_enough));
                                    break;
                                case Constant.NO_PAY_PASSWORD:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    showToast("没有支付密码");

                                    break;
                                case Constant.NEED_SETUP_PAY_PASSWORD_BEFORE:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    showToast("还没有设置支付密码");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(getString(R.string.pay_password_error));
                                    break;

                                case Constant.ORDER_INVALID:
                                    showToast("订单已经取消或者过期");
                                    syncOrderData(order.getId());
                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    showToast(getString(R.string.system_busy));
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));

                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 支付完成" + data.toJSONString());
                        showToast("支付完成");
                        order.setStatus(Constant.ORDER_STATUS_PAID);
                        order.setSendStatus(Constant.ORDER_SEND_STATUS_WAIT_SEND);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                        double totalBalance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        if (data.containsKey("deposit")) {
                            double deposit = data.getDouble("deposit");
                            //更新本地保证金
                            UserProfileManager.getInstance().setDeposit(deposit);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 订单发货
     */
    private void orderSend() {
        startActivityForResult(new Intent(this, OrderSendActivity.class).putExtra(Constant.EXTRA_INFO_ORDER, order), REQUEST_CODE_ORDER_SEND);
    }

    /**
     * 订单确认收货
     */
    private void receiveOrder() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .receive(order)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_cancelOrder, "订单确认收货完成");
                        order.setStatus(Constant.ORDER_SEND_STATUS_RECEIVED);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 同意退款
     */
    private void agreeRefund() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .agreeRefund(order)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_cancelOrder, "同意退款完成");
                        order.setStatus(Constant.ORDER_STATUS_REFUND_COMPLETED);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });

    }

    private void getFullTopic(String topicId) {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .get(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            return;
                        }
                        if (body.isError()) {
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取完成topic 完成");
                        JSONObject object = (JSONObject) body.getData();
                        if (object == null) {
                            return;
                        }
                        Topic topic = object.toJavaObject(Topic.class);
                        startActivity(new Intent(OrderDetailActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.INVISIBLE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }


    @Override
    public void onItemDelete(List<OrderReceiveInfo> orderReceiveInfoList) {
        User updateUser = new User();
        updateUser.setOrderReceiveInfoList(orderReceiveInfoList);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .updateUserInfo(updateUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 更新订单接收信息完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });

    }

    @Override
    public void onItemSelect(OrderReceiveInfo orderReceiveInfo) {

        et_contact.setText(orderReceiveInfo.getContact());
        et_phone.setText(orderReceiveInfo.getPhone());
        et_address.setText(orderReceiveInfo.getAddress());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_REFUND:
            case REQUEST_CODE_ORDER_SEND:
                order = data.getParcelableExtra(Constant.EXTRA_INFO_ORDER);
                setViewAndEvent();
                setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                break;
        }
    }
}
